/**
 * Created by TRwin7SP1 on 2016/8/15.
 */
angular.module('inspinia')
  .controller('Contouring02Controller',function ($scope,$timeout,$log,values,$interval,$http) {
    $scope.screenWidth = values.screen.Width;
    $scope.screenHeight = values.screen.Height;

    $scope.series={};
    $scope.detailTree = {
      // "height":values.screen.Height-217-157,
      "background-color":"#404040",
    };

    //工具栏
    $scope.btns = lmViewer.ui.config.buttons;

    var nodeNum = 4;//image struct节点的个数
    var clientHeight = document.documentElement.clientHeight;
    var structuresList = null;
    //打开勾靶开关
    lmViewer.data.RT.isContour = true;

    var picIndex=1;
    var scrollFunc=function(e){
      // console.log("index44:"+e);
      e=e || window.event;
      var _value=0;
      if(e.wheelDelta){//IE/Opera/Chrome
        _value=e.wheelDelta;
      }else if(e.detail){//Firefox
        _value=e.detail;
      }
      var index = _value%16;
      if (index > 1) {
        picIndex += 1;
      }else{
        picIndex -= 1;
      }
      picIndex=Math.abs(picIndex%16);
      // console.log("picIndex:"+picIndex);
      $("#centerImage").attr("src","assets/images/Contouring/caputure"+picIndex+".PNG")

    };

    $('body').addClass('mini-navbar');

    var init = function(){
      //获取structure列表
      var url =lm.environment("RTlocalserver").hostUrl+'/api/structure/ROIPlane';
      $http.get(url).then(function(response){

        structuresList = response.data;
        $scope.treeConfig4 = {
          'plugins' : [ 'types', 'dnd',"checkbox" ],
          'types' : {
            'default' : {
              'icon' : 'fa fa-folder'
            },
            'html' : {
              'icon' : 'fa fa-file-code-o'
            },
            'svg' : {
              'icon' : 'fa fa-file-picture-o'
            },
            'css' : {
              'icon' : 'fa fa-file-code-o'
            },
            'img' : {
              'icon' : 'fa fa-file-image-o'
            },
            'js' : {
              'icon' : 'fa fa-file-text-o'
            }

          }
        };
        $scope.treeData4 = [
          {
            "id": "ajson1",
            "parent": "#",
            "text": "image：TRstruct",
            "state": {
              "opened": true
            },
            "__uiNodeId": 1
          }, {
            "id": "ajson2",
            "parent": "ajson1",
            "text": "Registered Images",
            "state": {
              "opened": true
            },
            "__uiNodeId": 2
          }, {
            "id": "ajson3",
            "parent": "ajson2",
            "text": "Structure Set:CT_1",
            "state": {
              "opened": true
            },
            "type": "css",
            "__uiNodeId": 3
          },
          {
            "id": "RTstruct",
            "parent": "ajson1",
            "text": "Structure Set:RTstruct",
            "state": {
              "opened": true
            },
            "__uiNodeId": 6
          },
        ];

        angular.forEach(structuresList,function (data,index,array) {
          var _obj =  {
            "id": index+"_"+ data.fileName,
            "parent": "RTstruct",
            "text": data.name,
            "state": {
              "opened": true
            },
            "type":"img",
            "__uiNodeId": nodeNum+index
          };
          $scope.treeData4.push(_obj);
        });

      });
    };

    init();
    //判断数据是否已经存在
    var isContain = function(data){
      for(var n=0;n<lmViewer.data.RT.imageLines.length;n++){
        if(lmViewer.data.RT.imageLines[n].fileName == data)
          return n;
      }
      return -1;
    };

    $scope.treeEventsObj = {
      'ready': readyCB,
      'create_node': createNodeCB
    }

    function readyCB() {
      $log.info('ready called treeEventsObj');
    };
    function createNodeCB(e,item) {
      $log.info('create_node called treeEventsObj');
    };


      /**
       *
       */
    $scope.changeIconColor=function () {

      // $scope.treeInstance4.jstree(true).open_all();

      // $scope.treeInstance4.jstree(true).open_all();

      $scope.treeInstance4.jstree(true).select_node(["ajson3","ajson4"]);
      $scope.treeInstance4.jstree('select_node', 'ajson17');
      $scope.selected_nodeIDs = $scope.treeInstance4.jstree(true).get_selected();
      $scope.selected_nodes=_.filter($scope.treeData4,function(tree){
        return _.contains($scope.selected_nodeIDs,tree.id);
      });

      $scope.myObj = {
        "color" : "white",
        "background-color" : "coral",
        "font-size" : "60px",
        "padding" : "50px"
      };
    };

    $scope.readyCB=function () {
      $log.info(" JStree readyCB is running...");

      $scope.selected_nodeIDs = $scope.treeInstance4.jstree(true).get_selected();

      $scope.selected_nodes=_.filter($scope.treeData4,function(tree){
        return _.contains($scope.selected_nodeIDs,tree.id);
      });

      $timeout(function () {
        //设置颜色
        angular.forEach( structuresList,function (data,index,array) {
         $('#'+index+"_"+ data.fileName+">a>i").css('color','rgb('+data.color+')');
         });
      },100);

    }


    $scope.loadedCB=function () {
      // $log.info(" JStree loadedCB is running..."+$.jstree.defaults.plugins);
      // $("#ajson15>a>i").css("color","fuchsia");
      // $("#ajson16>a>i").css("color","orange");
      // $("#ajson17>a>i").css("color","red");
    };

      /**
       * qqqqqqq
       */
    $scope.initCB=function () {
      $log.info(" JStree initCB is running...");

    };

    $scope.load_allCB=function () {
      $log.info(" JStree load_allCB is running...");

    };

    /**
     * Options for Line chart
     */
    $scope.lineOptions = {
      scaleShowGridLines : true,
      scaleGridLineColor : "rgba(0,0,0,.05)",
      scaleGridLineWidth : 1,
      bezierCurve : true,
      bezierCurveTension : 0.4,
      pointDot : true,
      pointDotRadius : 4,
      pointDotStrokeWidth : 1,
      pointHitDetectionRadius : 20,
      datasetStroke : true,
      datasetStrokeWidth : 2,
      datasetFill : true
    };
    //
    $scope.lisnerID = $interval(function () {
      if(lmViewer.data.flag==true){
        $interval.cancel($scope.lisnerID);
        $scope.treeConfig1 = {
          'plugins' : [ 'types'],
          'types' : {
            'default' : {
              'icon' : 'fa fa-folder'
            },
            'user' : {
              'icon' : 'fa fa-user'
            },
            'book' : {
              'icon' : 'fa fa-book'
            },
            'css' : {
              'icon' : 'fa fa-file-code-o'
            },
            'img' : {
              'icon' : 'fa fa-file-image-o'
            },
            'js' : {
              'icon' : 'fa fa-file-text-o'
            }

          }
        };
        $scope.treeData1 = [
          {
            "id": "paitient",
            "parent": "#",
            "text": "Patient:"+lmViewer.data.queryParams.patId,
            "state": {
              "opened": true
            },
            "type": "user",
            "__uiNodeId": 1
          }, {
            "id": "study",
            "parent": "paitient",
            "text": "Study:"+lmViewer.data.queryParams.studyUID,
            "state": {
              "opened": true
            },
            "__uiNodeId": 2
          },
          {
            "id": "course",
            "parent": "paitient",
            "text": "Course: C1",
            "state": {
              "opened": true
            },
            "__uiNodeId": 5
          },
          {
            "id": "plan",
            "parent": "course",
            "text": "Plan:plan1",
            "state": {
              "opened": true
            },
            "type": "css",
            "__uiNodeId": 6
          },
        ];
        angular.forEach(lmViewer.data.series,function (data,index,array) {
          $scope.series={
            "id": index,
            "clickIndex":index,
            "parent": "study",
            "text": "Series:"+data.seriesDescription+''+data.numberOfInstances,
            "state": {
              "opened": true
            },
            "type": "book",
            "__uiNodeId": 3+index
          }
            $scope.treeData1.push($scope.series);
        });

      };
    },100);

    //点击切换事件

    $("#jstree_demo_div").bind('click',function () {
      $scope.indexImage=event.target.id.substr(0,1);
      $log.debug(event.target.id);
      lmViewer.ctrl.showSeriesByIndex($scope.indexImage);
    });

    //勾靶
/*    $('#jstree_TRstruct').bind("click.jstree", function () {
     // getvanvas();
      var _id = event.target.id.split('_');
      var _obj = {};
      var _containIndex = isContain(_id[1]);
      if(_containIndex > -1){
        lmViewer.data.RT.imageLines.splice(_containIndex,1);
        lmViewer.fn.RT.showImageLines();
      }
      else if(structuresList[_id[0]] && structuresList[_id[0]].fileName == _id[1]){

            _obj.fileName = structuresList[_id[0]].fileName;
            _obj.color = structuresList[_id[0]].color;
            lmViewer.data.RT.imageLines.push(_obj);
        lmViewer.fn.RT.getContourData(_obj.fileName);
      }

    });*/

    //设置高度
    var lisnerHeight = $interval(function () {
      if($('#TRviewerHeader').height()!=null && $('#title').height()!=null){
        $interval.cancel(lisnerHeight);
        $('#imageDiv').css('height',(clientHeight-$('div#TRviewerHeader').height()-$('#title').height()-5).toString()+'px');
        // $('#jstree_TRstruct').css('height',(clientHeight-$('div#TRviewerHeader').height()-$('#treeUp').height()-5).toString()+'px');
        $('#Scrollbar_TRstruct').css('height',(clientHeight-$('div#TRviewerHeader').height()-$('#treeUp').height()-5).toString()+'px');
        $('img').parent('.mBox-content').css('height',((clientHeight-$('div#TRviewerHeader').height()-3*$('#title').height()-13 )/3).toString() + 'px');
      }
    },50);

    //页面加载完成后显示滚动条
    $scope.$watch('$viewContentLoaded', function() {
      $(".content").mCustomScrollbar({
        axis:"yx"
      });
      // getvanvas();
    });

    var getvanvas = function(){
      var canvas = document.createElement('canvas');
      canvas.setAttribute('id','image00');

      canvas.width=1000;
      canvas.height=800;
      var myImage = document.getElementById('img');
      var ctx = canvas.getContext('2d');
      ctx.drawImage(myImage, 50, 50, 800, 800);
      $('#imageContainer').css('height','800px');
      document.getElementById('imageContainer').appendChild(canvas);
    };

//勾靶
    $scope.showLine = function () {

      var selectA=event.target.tagName=='A'?true:false;
      var _obj = {
        color: selectA?event.target.children[0].style.color:event.target.style.color,
        fileName: selectA?event.target.id.split("_")[1]:event.target.parentNode.id.split("_")[1],
      };


      var _containIndex = isContain(_obj.fileName);
      if(_containIndex > -1){
        lmViewer.data.RT.imageLines.splice(_containIndex,1);
        lmViewer.fn.RT.showImageLines();
      }
      else {
        lmViewer.data.RT.imageLines.push(_obj);
        lmViewer.fn.RT.getContourData(_obj.fileName);
      }
    }
  });
